<template>
  <div>
    <el-card>
      <el-page-header content="用户列表" icon="" title="用户管理" />
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column label="头像" width="180">
          <template #default="scope">
            <div v-if="scope.row.avatar">
              <el-avatar :size="50" :src="'http://localhost:3000' + scope.row.avatar" />
            </div>
            <div v-else>
              <el-avatar :size="50" :src="`https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色">
          <template #default="scope">
            <el-tag v-if="scope.row.role === 1" class="ml-2" type="danger">管理员</el-tag>
            <el-tag v-else class="ml-2" type="success">编辑</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-popconfirm title="您确定要删除吗?" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑用户" width="50%">
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="80px" status-icon class="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userForm.gender" class="m-2" placeholder="Select" style="width: 100%">
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" class="m-2" placeholder="Select" style="width: 100%">
            <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction">
          <el-input v-model="userForm.introduction" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
const dialogVisible = ref(false)
const tableData = ref([])
onMounted(() => {
  getTableData()
})
const userFormRef = ref()
// ref只能用于包装基本类型的数据，如数字、字符串等，而reactive可以用于包装任意类型的数据，包括对象、数组等
// ref返回的是一个包装后的对象，而reactive返回的是一个响应式的Proxy对象。
// ref可以直接通过.value属性获取包装的值，而reactive需要通过访问属性或者下标来获取值。
const userForm = ref({
  username: '',
  password: '',
  gender: 0,
  role: 2,
  introduction: ''
})
const userFormRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请选择密码', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入简介', trigger: 'blur' }]
})
// 性别选项
const options1 = [
  {
    label: '保密',
    value: 0
  },
  {
    label: '男',
    value: 1
  },
  {
    label: '女',
    value: 2
  }
]
// 角色选项
const options2 = [
  {
    label: '管理员',
    value: 1
  },
  {
    label: '编辑',
    value: 2
  }
]
const getTableData = async () => {
  const res = await axios.get('/adminapi/user/list')
  // console.log(res.data)
  tableData.value = res.data.data
}
// 点击编辑
const handleEdit = async (data) => {
  // console.log(data)

  const res = await axios.get(`/adminapi/user/list/${data._id}`)
  // console.log(res.data.data)
  userForm.value = res.data.data[0]
  dialogVisible.value = true
}
// 确认删除
const handleDelete = async (data) => {
  // console.log(data)
  await axios.delete(`/adminapi/user/list/${data._id}`)
  ElMessage.success('删除成功！')
  getTableData()
}
// 确认编辑
const handleEditConfirm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      // console.log(userForm.value)
      // 1.提交后端
      await axios.put(`/adminapi/user/list/${userForm.value._id}`, userForm)
      // 2.关闭对话框
      dialogVisible.value = false
      ElMessage.success('编辑成功！')
      // 3.更新table
      getTableData()
    }
  })
}
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 50px;
}
</style>
